package com.sos.service.impl;

import com.sos.exception.CustomException;
import com.sos.exception.ErrorCode;
import com.sos.model.entity.Notification;
import com.sos.repository.NotificationRepository;
import com.sos.service.NotificationService;
import com.sos.util.UserContextUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class NotificationServiceImpl implements NotificationService {

    private final NotificationRepository notificationRepository;
    private final UserContextUtils userContextUtils;

    @Override
    public void markAsRead(Long notificationId) {
        // 1. 获取当前用户
        Long userId = userContextUtils.getCurrentUserId();

        // 2. 查找通知并验证权限
        Notification notification = notificationRepository.findByIdAndUserId(notificationId, userId);
        if (notification == null) {
            throw new CustomException(ErrorCode.UNAUTHORIZED_OPERATION);
        }

        // 3. 更新状态为已读
        notification.setIsRead(1);
        notificationRepository.save(notification);
    }

    @Override
    public List<Notification> getHistoryNotifications(Long sinceId, Integer limit) {
        // 1. 获取当前用户
        Long userId = userContextUtils.getCurrentUserId();
        
        // 2. 创建分页对象
        Pageable pageable = PageRequest.of(0, limit != null ? limit : 20);
        
        // 3. 查询历史通知
        if (sinceId != null) {
            return notificationRepository.findAllByIdGreaterThanAndUserIdOrderByCreatedTimeDesc(sinceId, userId, pageable);
        } else {
            return notificationRepository.findByUserIdOrderByCreatedTimeDesc(userId, pageable);
        }
    }
}